/*
 * Copyright (C) 2017 - 2020 善林
 * File name:    StringUtil.java
 * Version:      1.0
 * Date:         2017-8-17
 * Description:  字符串处理的工具类，对空字符串做容错处理
 * Revision history: 
 * 2017-8-17   初始创建
 */
package com.wkbb.common.utils;

import java.util.List;
import java.util.UUID;
import java.util.regex.Pattern;

public class StringUtil {

	/**
	 * Function name:nullToString
	 * Description:以字符填充.
	 *
	 * @param str the str
	 * @return String
	 * @author: 研发中心
	 */
	public static String fillInChar(Object[] arr,String ch){
		if(arr==null || arr.length<1){
			return "";
		}
		StringBuilder sb = new StringBuilder();
		for(int i=0;i<arr.length;i++){
			sb.append(arr[i]+ch);
		}
		return sb.substring(0, sb.length()-ch.length());		
	}
	/**
	 * Function name:nullToString
	 * Description:以字符填充.
	 *
	 * @param str the str
	 * @return String
	 * @author: 研发中心
	 */
	public static String fillInChar(List<?> list,String ch){
		StringBuilder sb = new StringBuilder();
		for(int i=0;i<list.size();i++){
			sb.append(list.get(i)+ch);
		}
		return sb.substring(0, sb.length()-ch.length());		
	}
	/**
	 * Function name:nullToString
	 * Description:判断是否相等.
	 *
	 * @param str the str
	 * @return String
	 * @author: 研发中心
	 */
	public static boolean eq(String str1,String str2){
		str1 =nullToString(str1);
		str2 =nullToString(str2);		
		return str1.trim().toLowerCase().equalsIgnoreCase(str2.trim().toLowerCase());
	}
	/**
	 * Function name:nullToString
	 * Description: 对字符串做容错处理，null字符串对象就返回空字符串.
	 *
	 * @param str the str
	 * @return String
	 * @author: 研发中心
	 */
	public static String nullToString(String str){
		if(str==null || str.equals("null") || str.equals("NULL")){
			return "";
		}else{
			return str;
		}
	}
	
	/**
	 * 去掉前后空格.
	 *
	 * @param s 被检验的字符�?
	 * @return 去掉前后空格
	 */
	public static String trim(final String s) {
		if (s == null) {
			return s;
		}
		if (s.equals("undefined")||s.equalsIgnoreCase("null")) {
			return "";
		}
		return s.trim();
	}
	
	/**
	 * �?��传入的字符串是否为空.
	 *
	 * @param s 被检验的字符�?
	 * @return 如果字符串为空对象或空字符串，则返回true
	 */
	public static boolean isNullOrBlank(final String s) {
		if (s == null) {
			return true;
		}
		if (s.trim().equals("")) {
			return true;
		}
		return false;
	}
	
	/**
	 * 
	 * Function name: isNotEmpty
	 * Description: 判断传入值是否为空
	 * 
	 * @param str
	 * @return
	 * @data:	2017-4-15
	 
	 */
	public static boolean isNotEmpty(final String str) {
		return !isEmpty(str);
	}
	

    /**
     * 判断字符串是否为空(包含null与"")
     *
     * @param str
     * @return
     */
    public static boolean isEmpty(String str) {
        if (str == null || "".equals(str)|| "null".equals(str)) {
            return true;
        }
        return false;
    }

    /**
     * 判断字符串是否为空(包含null与"","    ")
     *
     * @param str
     * @return
     */
    public static boolean isEmptyIgnoreBlank(String str) {
        if (str == null || "".equals(str) || "".equals(str.trim())) {
            return true;
        }
        return false;
    }
    
    /**
     * 判断字符串是否为非空(包含null与"","    ")
     *
     * @param str
     * @return
     */
    public static boolean isNotEmptyIgnoreBlank(String str) {
        return !isEmptyIgnoreBlank(str);
    }
    
	/**
	 * Function name:ObjectToString
	 * Description: 将Object转化成字符串.
	 *
	 * @param obj the obj
	 * @return String
	 * @author: 研发中心
	 */
	public static String ObjectToString(Object obj){
		if(obj==null){
			return "";
		}else{
			String str = obj.toString();
			return nullToString(str);
		}
	}
		
	/**
	 * Function name:nullToString
	 * Description: 如果是空字符串就用fillStr填充.
	 *
	 * @param str the str
	 * @param fillStr the fill str
	 * @return String
	 * @author: 研发中心
	 */
	public static String fillToNullString(String str,String fillStr){
		if(str!=null){
			str=str.trim();
		}
		
		if(str==null || str.equals("null") || str.equals("") || str.equals("NULL")){
			return fillStr;
		}else{
			return str;
		}
	}
	
	/**
	 * Description: 脚本过滤方法
	 * @param inputString
	 * @return
	 * @data:	2017-5-15
	 
	 */
	public static String HtmlToText(String inputString) {
		String htmlStr = inputString; //含html标签的字符串 
		String textStr = "";
		Pattern p_script;
		java.util.regex.Matcher m_script;
		Pattern p_style;
		java.util.regex.Matcher m_style;
		Pattern p_html;
		java.util.regex.Matcher m_html;

		try {
			String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>"; //定义script的正则表达式{或<script[^>]*?>[\\s\\S]*?<\\/script> } 
			String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>"; //定义style的正则表达式{或<style[^>]*?>[\\s\\S]*?<\\/style> } 
			String regEx_html = "<[^>]+>"; //定义HTML标签的正则表达式 

			p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
			m_script = p_script.matcher(htmlStr);
			htmlStr = m_script.replaceAll(""); //过滤script标签 

			p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
			m_style = p_style.matcher(htmlStr);
			htmlStr = m_style.replaceAll(""); //过滤style标签 

			p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
			m_html = p_html.matcher(htmlStr);
			htmlStr = m_html.replaceAll(""); //过滤html标签 

			textStr = htmlStr;
		} catch (Exception e) {
			System.err.println("Html2Text: " + e.getMessage());
		}
		return textStr;//返回文本字符串 
	}
	/*
	 * 取异常堆栈信息
	 */
	public static String getExceptionStack(Exception e){
		StringBuilder sb = new StringBuilder();		
		sb.append(e.toString()+"\r\n");
		for(StackTraceElement elem : e.getStackTrace()) { 
			sb.append(elem+"\r\n"); 
		} 
		return sb.toString();
	}

	public static String getBusinessIdByUUId() {//11位
		int machineId = 1;
		int hashCodeV = UUID.randomUUID().toString().hashCode();
		if (hashCodeV < 0) {//有可能是负数
			hashCodeV = -hashCodeV;
		}
//         0 代表前面补充0     
//         4 代表长度为4     
//         d 代表参数为正数型
		return machineId + String.format("%010d", hashCodeV);
	}

	/**
	 * 生成服务期限月份字符串
	 * @param period
	 * @param currentMonth
	 * @return
	 */
	public static String getServiceLifeForMonth(int period,int  currentMonth) {
		//例如3,4,5,6,7,8,9,10,11,12,1,2,3,
		StringBuffer itemIds = new StringBuffer();
		for(int i=0;i<period;i++ ,currentMonth++){
			if(currentMonth>12){
				itemIds.append(currentMonth-12).append(",");
			}else{
				itemIds.append(currentMonth).append(",");
			}
		}
		return  itemIds.toString().substring(0,itemIds.length()-1);
	}

	/**
	 * 文件名乱码（我发现只要解决了文件名乱码，其他乱码也会跟着解决）response.setHeader("Content-disposition", "attachment; filename=中文.xls");
	 * 调用的时候,response.setHeader("Content-disposition", "attachment; filename="+toUtf8String("中文.xls"));
	 * @param s
	 * @return
	 */
	public static String toUtf8String(String s){
		StringBuffer sb = new StringBuffer();
		for (int i=0;i<s.length();i++){
			char c = s.charAt(i);
			if (c >= 0 && c <= 255){sb.append(c);}
			else{
				byte[] b;
				try { b = Character.toString(c).getBytes("utf-8");}
				catch (Exception ex) {
					System.out.println(ex);
					b = new byte[0];
				}
				for (int j = 0; j < b.length; j++) {
					int k = b[j];
					if (k < 0) k += 256;
					sb.append("%" + Integer.toHexString(k).toUpperCase());
				}
			}
		}
		return sb.toString();
	}
}
